package com.gdk.ksoft.ui.customers;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.gdk.ksoft.R;
import com.gdk.ksoft.data.common.ConstantData;
import com.gdk.ksoft.data.common.SystemData;
import com.gdk.ksoft.data.entry.datas.BaseResultModel;
import com.gdk.ksoft.data.entry.tables.DeliverGoodsTable;
import com.gdk.ksoft.ui.customers.adapters.CustomerAddrAdapter;
import com.gdk.ksoft.ui.customers.models.AddrInfoModel;
import com.gdk.ksoft.assembly.dialog.CustomerAddrEditDialog;
import com.gdk.ksoft.assembly.dialog.MessageBox;
import com.gdk.ksoft.assembly.utils.system.FileUtils;
import com.gdk.ksoft.assembly.utils.extensions.MD5Utils;
import com.gdk.ksoft.assembly.utils.system.NetworkUtils;
import com.gdk.ksoft.assembly.utils.system.SQLiteUtils;
import com.google.gson.Gson;
import com.lidroid.xutils.DbUtils;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.client.HttpRequest;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.lidroid.xutils.view.annotation.event.OnItemClick;
import com.lidroid.xutils.view.annotation.event.OnItemLongClick;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * 客户信息维护页面
 */
public class NewDeliverAddressActivity extends Activity {

    @ViewInject(R.id.pnewdeliverAddr_txtCustomerName)private TextView txtCustomerName;//客户名称
    @ViewInject(R.id.pnewdeliverAddr_lstaddress)private ListView lstAddress;//地址列表

    private List<AddrInfoModel> addrInfoList = new ArrayList<>();//客户地址列表信息
    private CustomerAddrAdapter adapter;//地址数据填充器
    private int customerId = 0;//客户ID

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_new_deliveraddress);
        ViewUtils.inject(this);
        Intent intent = getIntent();
        if(intent!=null && intent.hasExtra("customerId")){//获取客户ID
            customerId = intent.getIntExtra("customerId",0);
            txtCustomerName.setText("客户名称："+intent.getStringExtra("customerName"));
        }
        adapter = new CustomerAddrAdapter(this,addrInfoList);
        lstAddress.setAdapter(adapter);
    }

    /**
     * 界面控件点击事件响应
     * @param view
     */
    @OnClick(value = {R.id.pnewdeliverAddr_imgAdd,R.id.pnewdeliverAddr_txtSubmit,R.id.pnewdeliverAddr_txtCancel})
    public void onViewClick(View view){
        switch(view.getId()){
            case R.id.pnewdeliverAddr_imgAdd://添加地址
                showAddrDialog();//显示客户地址窗口
                break;
            case R.id.pnewdeliverAddr_txtCancel://取消
                goBack();//页面返回
                break;
            case R.id.pnewdeliverAddr_txtSubmit://添加新客户
                executeAddDeliverAddressTask(this,addrInfoList);//执行添加地址的任务
                break;
        }
    }

    /**
     * 执行添加地址的任务
     */
    public void executeAddDeliverAddressTask(final Context context,final List<AddrInfoModel> datalist){
        new AsyncTask<Void,Void,Void>(){
            private boolean isExcuteOk = true;
            private ProgressDialog dialog = null;
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                dialog = ProgressDialog.show(context,"","正在执行操作...");
            }

            @Override
            protected Void doInBackground(Void... params) {
                isExcuteOk = addCustomerAddressList(datalist);
                return null;
            }

            @Override
            protected void onPostExecute(Void aVoid) {
                super.onPostExecute(aVoid);
                if(dialog != null && dialog.isShowing()) dialog.dismiss();
                if(!isExcuteOk)
                    Toast.makeText(context,"添加失败,请重试!",Toast.LENGTH_SHORT).show();
                else{
                    addrInfoList.clear();
                    adapter.notifyDataSetChanged();
                    showAlertGoOnDialog();//显示继续添加的提示框
                }
            }
        }.execute();
    }

    /**
     * 显示继续添加的提示框
     */
    public void showAlertGoOnDialog(){
        final MessageBox msgBox = new MessageBox(this);
        msgBox.setMessage("添加成功是否继续添加!");
        msgBox.setCancelable(false);
        msgBox.setCanceledOnTouchOutside(false);
        msgBox.onPositiveNegitiveClick(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (v.getId()){
                    case MessageBox.ID_DIALOG_BUTTON_CANCEL:
                        goBack();//关闭当前页面
                        break;
                    default:
                        break;
                }
                msgBox.dismiss();
            }
        });
        msgBox.show();
    }

    /**
     * 添加客户地址到本地数据库(选中某一个客户时使用)
     * @param addrInfos
     * @return true - 添加成功  false - 添加失败
     */
    public boolean addCustomerAddressList(List<AddrInfoModel> addrInfos){
        boolean isOk = true;
        DbUtils dbUtils = SQLiteUtils.getInstance(this).getDbUtils();
        SQLiteDatabase sqLiteDatabase = dbUtils.getDatabase();
        if(addrInfos!=null && addrInfos.size()>0){
            try {
                sqLiteDatabase.beginTransaction();
                for (AddrInfoModel data : addrInfos) {
                    DeliverGoodsTable item = new DeliverGoodsTable();
                    item.id = 0;
                    item.kh_id = customerId;
                    item.djbz = 0;
                    item.dq_id = data.intCarea;
                    item.jc = data.abbr;
                    if (SystemData.currentLocation != null) {
                        item.jwd = SystemData.currentLocation.getLatitude() + "," + SystemData.currentLocation.getLongitude();
                    }
                    item.jymj = TextUtils.isEmpty(data.addrArea) ? 0 : Integer.parseInt(data.addrArea);
                    item.khlx = data.intCtype;
                    item.shdh = data.connectity;
                    item.shdz = data.addr;
                    item.shfs = 2;//暂时默认为2
                    item.shr = data.contractor;
                    isOk = uploadDeliverAddress(NewDeliverAddressActivity.this,item,dbUtils);//上传客户收货地址，如果失败则直接存入本地
                }
                sqLiteDatabase.setTransactionSuccessful();
            }catch (Exception e){
                e.printStackTrace();
                isOk = false;
            }
            sqLiteDatabase.endTransaction();
        }
        return isOk;
    }

    /**
     * 上传客户收货地址，如果失败则直接存入本地
     */
    public static boolean uploadDeliverAddress(final Context context,final DeliverGoodsTable item,DbUtils dbUtils)throws Exception{
        if(NetworkUtils.isNetAvailable(context)) {
            HttpUtils httpUtils = new HttpUtils(ConstantData.NETWORK_CONNECT_TIME_OUT).configSoTimeout(ConstantData.NETWORK_READ_TIME_OUT);
            String methodName = "Cx_UpKhShdz";
            String messageBody = "{\"Sjch\":\"" + SystemData.PhoneIMEI + "\",\"Data\":{\"upShdz\":"+new Gson().toJson(item)+"}}";
            System.out.println("-----> 正在上传客户收货地址数据：" + messageBody);
            RequestParams params = new RequestParams("UTF-8");
            params.addBodyParameter("Method", methodName);
            params.addBodyParameter("Digest", MD5Utils.getMd5(methodName + messageBody + "19491001"));
            params.addBodyParameter("MessageBody", messageBody);
            InputStream is = httpUtils.sendSync(HttpRequest.HttpMethod.POST, SystemData.BASE_URL, params);
            String result = FileUtils.stream2string(is, "utf-8");
            System.out.println("----->上传客户收货地址结果："+result);
            if (!TextUtils.isEmpty(result)) {
                BaseResultModel resultModel = new Gson().fromJson(result, BaseResultModel.class);
                if (resultModel.Result.equals("0000")) {
                    item.djbz = 1;//修改单机标识
                    item.id = Integer.parseInt(resultModel.Data);//返回的自增长ID
                    dbUtils.save(item);
                    return true;
                }
            }
        }
//        dbUtils.save(item);
        return false;
    }

    /**
     * 地址列表点击事件
     * @param av
     * @param view
     * @param position
     * @param itemId
     */
    @OnItemClick(value = {R.id.pnewdeliverAddr_lstaddress})
    public void onItemClick(AdapterView<?> av,View view,int position,long itemId){
        showEditAddrDialog(position, addrInfoList.get(position));//显示编辑客户信息提示框
    }

    /**
     * 地址列表长按事件
     * @param parent
     * @param view
     * @param position
     * @param id
     * @return
     */
    @OnItemLongClick(value = {R.id.pnewdeliverAddr_lstaddress})
    public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
        showDelDialog(position);//显示删除提示框
        return true;
    }

    /**
     * 显示删除提示框
     * @param position
     */
    public void showDelDialog(final int position){
        final MessageBox msgBox = new MessageBox(this);
        msgBox.setMessage("确定要删除该新增的地址信息吗？");
        msgBox.onPositiveNegitiveClick(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (v.getId()) {
                    case MessageBox.ID_DIALOG_BUTTON_OK:
                        addrInfoList.remove(position);
                        adapter.notifyDataSetChanged();
                        break;
                    default:
                        break;
                }
                msgBox.dismiss();
            }
        });
        msgBox.show();
    }

    /**
     * 显示新增客户地址窗口
     */
    public void showAddrDialog(){
        final CustomerAddrEditDialog dialog = new CustomerAddrEditDialog(this,"添加新地址");
        dialog.setOnValueChangedListener(new CustomerAddrEditDialog.OnValueChangedListener() {
            @Override
            public void onValueChanged(AddrInfoModel info) {
                addrInfoList.add(info);
                adapter.notifyDataSetChanged();
            }
        });
        dialog.show();
    }

    /**
     * 显示编辑客户信息提示框
     * @param addrInfo
     */
    public void showEditAddrDialog(final int position, final AddrInfoModel addrInfo){
        final CustomerAddrEditDialog dialog = new CustomerAddrEditDialog(this,"修改客户地址",addrInfo);
        dialog.setOnValueChangedListener(new CustomerAddrEditDialog.OnValueChangedListener() {
            @Override
            public void onValueChanged(AddrInfoModel info) {
                addrInfoList.set(position,addrInfo);
                adapter.notifyDataSetChanged();
            }
        });
        dialog.show();
    }

    /**
     * 页面返回
     */
    public void goBack() {
        this.finish();
        overridePendingTransition(android.R.anim.slide_in_left, android.R.anim.slide_out_right);
    }

    @OnClick(value = {R.id.pnewdeliverAddr_imgBack})
    public void OnBackClick(View view) {
        goBack();//页面返回
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (event.getAction() == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_BACK) {
            goBack();//页面返回
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
